/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja.data;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Represents the path to a box file.
 */
public class BoxFilePath implements BoxFile {
    private final String name;
    private final String[] components;
    
    private BoxFilePath(String[] components) {
        this.name = components[components.length - 1];
        this.components = new String[components.length - 1];
        System.arraycopy(components, 0, this.components, 0, components.length - 1);      
    }
    
    public BoxFilePath(String path) {
        if (!path.startsWith("/")) {
            throw new IllegalArgumentException("Invalid FilePath: " + path);
        }
        
        List<String> pathComponents = new ArrayList<String>();
        pathComponents.add("");
        
        for (StringTokenizer strTok = new StringTokenizer(path.substring(1, path.length()), "/"); strTok.hasMoreTokens(); ) {
            String pathComponent = strTok.nextToken();
            if ("..".equals(pathComponent) || ".".equals(pathComponent)) {
                throw new IllegalArgumentException("Invalid path component in FilePath: " + path + " (" +  pathComponent + ")");
            }
            pathComponents.add(pathComponent);    
        }
        
        int pathSize = pathComponents.size();
        if (pathSize > 1) {
            this.name = pathComponents.get(pathSize - 1);
            this.components = pathComponents.subList(0, pathSize - 1).toArray(new String[pathSize - 1]);
        } else {
            this.name = "";
            this.components = new String[] {};
        }
    }
    
    public boolean isRoot() {
        return "".equals(this.name) && this.components.length == 0;
    }
    
    public BoxFilePath getParent() {
        if (isRoot()) {
            return null;
        } else {
            return new BoxFilePath(this.components);
        }
    }
    
    public String getName() {
        return this.name;    
    }
    
    public String getPath() {       
        StringBuilder path = new StringBuilder();
        for (String component : this.components) {
            path.append(component).append('/');
        } 

        path.append(this.name);

        return path.toString();
    }
    
    public String toString() {
        return getPath();
    }
}
